Page({
  data: {
    // 日历数据
    calendarData: [],
    // 排行榜数据
    leaderboardData: [
      {
        id: 1,
        rank: 1,
        username: '学习之星',
        avatar: '/static/icons/avatar-placeholder.png',
        studyTime: 480, // 8小时
        points: 1250
      },
      {
        id: 2,
        rank: 2,
        username: '勤奋小蜜蜂',
        avatar: '/static/icons/avatar-placeholder.png',
        studyTime: 420, // 7小时
        points: 1180
      },
      {
        id: 3,
        rank: 3,
        username: '努力向上',
        avatar: '/static/icons/avatar-placeholder.png',
        studyTime: 360, // 6小时
        points: 980
      },
      {
        id: 4,
        rank: 4,
        username: '小明同学',
        avatar: '/static/icons/avatar-placeholder.png',
        studyTime: 300, // 5小时
        points: 850,
        isCurrentUser: true
      },
      {
        id: 5,
        rank: 5,
        username: '坚持不懈',
        avatar: '/static/icons/avatar-placeholder.png',
        studyTime: 240, // 4小时
        points: 720
      }
    ], // 测试排行榜数据
    // 消息提示相关
    showMessage: false,
    messageText: '',
    messageType: 'info'
  },

  onLoad() {
    console.log('成就页面加载');
    
    // 检查登录状态
    this.checkLoginStatus();
    
    // 加载数据
    this.loadAchievementData();
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('local_token');
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      wx.navigateTo({
        url: '/subpkg/pages/login/login'
      });
      return false;
    }
    return true;
  },
  
  // 加载成就数据
  async loadAchievementData() {
    await Promise.all([
      this.loadStudyCalendar(),
      this.loadLeaderboard()
    ]);
  },
  
  // 加载学习日历数据 - 模拟版本
  async loadStudyCalendar() {
    const token = wx.getStorageSync('local_token');
    if (!token) {
      this.generateCalendar();
      return;
    }

    try {
      // 模拟延迟
      await new Promise(resolve => setTimeout(resolve, 300));
      
      // 模拟日历数据
      const mockCalendarData = {};
      const today = new Date();
      const currentMonth = today.getMonth();
      const currentYear = today.getFullYear();
      const currentDate = today.getDate();
      
      // 为当月的一些日期添加学习记录
      const testDates = [1, 3, 5, 7, 8, 10, 12, 14, 15, 17, 19, 21, 22, 24, 26, 28];
      testDates.forEach(date => {
        if (date <= currentDate) {
          const dateStr = `${currentYear}-${String(currentMonth + 1).padStart(2, '0')}-${String(date).padStart(2, '0')}`;
          mockCalendarData[dateStr] = {
            total_minutes: Math.floor(Math.random() * 300) + 60, // 1-5小时的随机学习时间
            sessions: Math.floor(Math.random() * 3) + 1 // 1-3个学习会话
          };
        }
      });
      
      this.generateCalendar(mockCalendarData);
    } catch (error) {
      console.error('加载学习日历失败:', error);
      this.generateCalendar();
    }
  },
  
  // 生成日历数据
  generateCalendar(studyData = {}) {
    const today = new Date();
    const currentMonth = 7; // 8月（月份从0开始，所以7代表8月）
    const currentYear = today.getFullYear();
    const currentDate = today.getDate();
    
    // 生成测试学习数据
    if (Object.keys(studyData).length === 0) {
      // 为当月的一些日期添加学习记录
      const testDates = [1, 3, 5, 7, 8, 10, 12, 14, 15, 17, 19, 21, 22, 24, 26, 28];
      testDates.forEach(date => {
        if (date <= currentDate) {
          const dateStr = `${currentYear}-${String(currentMonth + 1).padStart(2, '0')}-${String(date).padStart(2, '0')}`;
          studyData[dateStr] = {
            study_time: Math.floor(Math.random() * 300) + 60, // 1-5小时的随机学习时间
            sessions: Math.floor(Math.random() * 3) + 1 // 1-3个学习会话
          };
        }
      });
    }
    
    // 获取当月第一天和最后一天
    const firstDay = new Date(currentYear, currentMonth, 1);
    const lastDay = new Date(currentYear, currentMonth + 1, 0);
    const daysInMonth = lastDay.getDate();
    
    // 获取第一天是星期几（0=周日，1=周一...）
    const firstDayOfWeek = firstDay.getDay();
    
    const calendarData = [];
    
    // 添加空白天数（上个月的日期）
    for (let i = 0; i < firstDayOfWeek; i++) {
      calendarData.push({
        day: '',
        studyClass: '',
        studyHours: 0,
        isToday: false
      });
    }
    
    // 添加当月的日期
    for (let day = 1; day <= daysInMonth; day++) {
      const dateKey = `${currentYear}-${String(currentMonth + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
      const dayData = studyData[dateKey];
      
      // 使用真实数据
      const studyMinutes = dayData?.total_minutes || 0;
      const studyHours = studyMinutes / 60;
      
      let studyLevel = 0;
      if (studyHours === 0) {
        studyLevel = 0;
      } else if (studyHours <= 1) {
        studyLevel = 1;
      } else if (studyHours <= 2) {
        studyLevel = 2;
      } else if (studyHours <= 4) {
        studyLevel = 3;
      } else if (studyHours <= 6) {
        studyLevel = 4;
      } else {
        studyLevel = 5;
      }
      
      // 判断是否是今天
      const isToday = currentDate === day && currentMonth === today.getMonth();
      
      calendarData.push({
        day: day,
        studyClass: `study-${studyLevel}`,
        studyHours: studyHours,
        isToday: isToday
      });
    }
    
    this.setData({
      calendarData: calendarData
    });
  },
  
  // 加载排行榜数据 - 模拟版本
  async loadLeaderboard() {
    const token = wx.getStorageSync('local_token');
    if (!token) return;
    
    try {
      // 模拟延迟
      await new Promise(resolve => setTimeout(resolve, 300));
      
      // 模拟排行榜数据
      const mockRankings = [
        { user_id: 1, nickname: '学霸小明', total_minutes: 720, rank: 1 },
        { user_id: 2, nickname: '努力的小红', total_minutes: 680, rank: 2 },
        { user_id: 3, nickname: '进步的小刚', total_minutes: 650, rank: 3 },
        { user_id: 4, nickname: '坚持的小丽', total_minutes: 600, rank: 4 },
        { user_id: 5, nickname: '勤奋的小强', total_minutes: 580, rank: 5 },
        { user_id: 6, nickname: '认真的小芳', total_minutes: 550, rank: 6 },
        { user_id: 7, nickname: '专注的小华', total_minutes: 520, rank: 7 },
        { user_id: 8, nickname: '自律的小军', total_minutes: 500, rank: 8 },
        { user_id: 9, nickname: '好学的小敏', total_minutes: 480, rank: 9 },
        { user_id: 10, nickname: '刻苦的小杰', total_minutes: 450, rank: 10 }
      ];
      
      const leaderboardData = mockRankings.map((user) => ({
        name: user.nickname,
        time: this.formatStudyTime(user.total_minutes || 0),
        rankClass: this.getRankClass(user.rank),
        rankIcon: this.getRankIcon(user.rank)
      }));
      
      this.setData({
        leaderboardData: leaderboardData
      });
    } catch (error) {
      console.error('加载排行榜失败:', error);
      // 保持默认排行榜数据
    }
  },
  
  // 格式化学习时间
  formatStudyTime(minutes) {
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    if (hours > 0) {
      return `${hours}小时${mins}分钟`;
    }
    return `${mins}分钟`;
  },
  
  // 获取排名样式
  getRankClass(rank) {
    if (rank === 1) return 'gold';
    if (rank === 2) return 'silver';
    if (rank === 3) return 'bronze';
    return 'normal';
  },
  
  // 获取排名图标
  getRankIcon(rank) {
    if (rank === 1) return '👑';
    if (rank === 2) return '🥈';
    if (rank === 3) return '🥉';
    return `${rank}`;
  },

  // 日历日期点击事件
  onDayClick(e) {
    const { day, hours } = e.currentTarget.dataset;
    if (!day) return;
    
    const studyHours = parseFloat(hours) || 0;
    let messageText = '';
    let messageType = 'info';
    
    if (studyHours > 0) {
      messageText = `8月${day}日学习了${studyHours.toFixed(1)}小时`;
      messageType = 'success';
    } else {
      messageText = `8月${day}日未学习`;
      messageType = 'info';
    }
    
    this.showMessage(messageText, messageType);
  },

  // 排行榜点击事件
  onLeaderboardClick(e) {
    const { name, time } = e.currentTarget.dataset;
    const messageText = `${name}的学习时长：${time}`;
    this.showMessage(messageText, 'info');
  },

  // 显示消息提示
  showMessage(text, type = 'info') {
    // 如果已经有消息在显示，先隐藏
    if (this.data.showMessage) {
      this.setData({
        showMessage: false
      });
      // 等待动画完成后再显示新消息
      setTimeout(() => {
        this.displayMessage(text, type);
      }, 300);
    } else {
      this.displayMessage(text, type);
    }
  },

  // 显示消息
  displayMessage(text, type) {
    this.setData({
      messageText: text,
      messageType: type,
      showMessage: true
    });
    
    // 3秒后自动隐藏
    setTimeout(() => {
      this.setData({
        showMessage: false
      });
    }, 3000);
  },

  // Tab切换事件
  onTabSwitch(e) {
    const url = e.currentTarget.dataset.url;
    wx.switchTab({
      url: url
    });
  },
  
  // 刷新数据
  onRefresh() {
    this.loadAchievementData();
  },
  
  // 页面显示时刷新数据
  onShow() {
    this.onRefresh();
  }
});

